//
//  UIView+RSSingleTap.m
//  RSTools
//
//  Created by thinkjoy on 2017/9/12.
//  Copyright © 2017年 杜瑞胜. All rights reserved.
//

#import "UIView+RSSingleTap.h"
#import <objc/runtime.h>

/**
 *  动态添加手势
 */
static const char *ActionHandlerTapGestureKey = "ActionHandlerTapGestureKey";

#define WeakSelf(weakSelf)  __weak __typeof(&*self)weakSelf = self;

@implementation UIView (RSSingleTap)


- (void)setTapActionWithBlock:(void (^)(void))block{
    self.userInteractionEnabled = YES;
    
    //    UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &ActionHandlerTapGestureKey);
    //
    //    if (!gesture) {
    //        gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForTapGesture:)];
    //        [self addGestureRecognizer:gesture];
    //        objc_setAssociatedObject(self, &ActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    //    }
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForTapGesture:)];
    [self addGestureRecognizer:gesture];
    
    objc_setAssociatedObject(self, &ActionHandlerTapGestureKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void)handleActionForTapGesture:(UITapGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateRecognized)  {
        void(^action)(void) = objc_getAssociatedObject(self, &ActionHandlerTapGestureKey);
        if (action)  {
            action();
        }
    }
}

//-(void)buttonClick{
//    void(^action)(void) = objc_getAssociatedObject(self, @selector(buttonClick));
//    if (action)  {
//        action();
//    }
//}
@end
